from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group


class PermissionAdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

        # 创建时无法加密密码，所以要重写

    def create(self, validated_data):
        # 获取用户
        user = super().create(validated_data)

        # 2,设置管理员密码加密
        user.is_superuser = True
        user.is_staff = True
        user.set_password(validated_data["password"])
        user.save()

        # 3,返回
        return user

        # 修改时无法加密密码，所以要重写

    def update(self, instance, validated_data):
        # 2,重写update方法,密码加密
        def update(self, instance, validated_data):
            # 1,更新普通信息
            user = super().update(instance, validated_data)

            # 2,密码加密
            user.set_password(validated_data["password"])
            user.save()

            # 3,返回
            return user


class PermissionGroupAdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ("id", "name")


